package com.example.devinfan.criminalintent.model;

import android.content.Context;
import android.util.Log;

import java.util.ArrayList;
import java.util.UUID;

public class CrimeLab {
    private ArrayList<Crime> mCrimes;
    private static  CrimeLab sCrimeLab;
    private Context mAppContext;
    private static final String TAG = "CrimeLab";
    private static final String FILENAME = "crimes.json";
    private CriminalIntentJSONSerialier mSerialier;


    private CrimeLab(Context appContext){
        mAppContext = appContext;
        mSerialier = new CriminalIntentJSONSerialier(mAppContext,FILENAME);
        try{
            mCrimes = mSerialier.loadCrimes();
        }catch (Exception e){
            mCrimes = new ArrayList<>();
            Log.e(TAG,"Error loading crimes: " ,e);
        }

    }

    //删除一个crime项要删除图片！
    public void deleteCrime(Crime c){
        mCrimes.remove(c);
    }

    public ArrayList<Crime> getCrimes(){
        return mCrimes;
    }

    public Crime getCrime(UUID id){
        for(Crime c : mCrimes) {
            if (c.getId().equals(id)) {
                return c;
            }
        }
        return null;
    }

    public void addCrime(Crime c){
        mCrimes.add(c);
    }

    public static CrimeLab get(Context c){
        if(sCrimeLab == null){
            sCrimeLab = new CrimeLab(c.getApplicationContext());
        }
        return sCrimeLab;
    }

    public boolean saveCrimes(){
        try{
            mSerialier.saveCrimes(mCrimes);
            Log.d(TAG, "crimes saved to file");
            return true;
        }catch (Exception e){
            Log.e(TAG,"Error saving crimes: ",e);
            return false;
        }
    }

}
